import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'package:umeng_push_demo/controller/app_controller.dart';
import 'package:umeng_push_demo/model/local_notifications.dart';
import 'package:umeng_push_demo/model/push_message_model.dart';
import 'package:umeng_push_sdk/umeng_push_sdk.dart';

/// FileName PushManager
///
/// @Author 陈晓星
/// @Date 2024/10/25 08:44
///
/// @Description TODO

const _Channel = 'App';

class PushManager {
  /// 初始化
  static Future<void> initial() async {
    /**
     * cxx
     * Android:
     * App Key：671a073780464b33f6e3ee66
     * App Master Secret：jzdxhpgygcdprvnp0sl0dqb72sg96osq
     * Umeng Message Secret：5ec8d8ce59d66ccb539571651ed2b6dd
     * iOS:
     * App Key：6721ca2d7334e114d3a9def0
     * App Master Secret: 3uswpybemlkqa0l8broie04wycxzxznv
     *
     * csj
     * App Key：671f3982667bfe33f3cc1c52
     * App Master Secret：74936706b463d7fcf6f6cc853c5281d6
     * Umeng Message Secret：6ytsnferujew2ga3u42bjmyspgjje8kc
     */
    UmengPushSdk.setLogEnable(true);
    UmengCommonSdk.initCommon(
        "671a073780464b33f6e3ee66",
        "6721ca2d7334e114d3a9def0",
        _Channel,
    );
    if (Platform.isAndroid) {
      UmengPushSdk.register("671a073780464b33f6e3ee66", "App");
    } else {
      UmengPushSdk.register("6721ca2d7334e114d3a9def0", "AppStore");
    }

    String? alias = await PushManagerSP.getAliasLocal();
    if (alias != null && alias.isNotEmpty) {
      UmengPushSdk.setAlias(alias, _Channel);
    }
    String? tag = await PushManagerSP.getTagLocal();
    if (tag != null && tag.isNotEmpty) {
      UmengPushSdk.addTags([tag]);
    }

    // Android Token回调
    if (Platform.isAndroid) {
      UmengPushSdk.setTokenCallback((result) {
        final appController = Get.put(AppController());
        appController.deviceToken.value = result;
        print('>>> android deviceToken: $result');
      });
    } else {
      String? registeredId = await UmengPushSdk.getRegisteredId();
      if (registeredId != null) {
        final appController = Get.put(AppController());
        appController.deviceToken.value = registeredId;
        print('>>> iOS registeredId: $registeredId');
      }
    }

    // 通知消息回调（到达：receive，点击：open）
    UmengPushSdk.setNotificationCallback((result) async {
      print("接收到消息：$result");
      AppController appController = Get.put(AppController());
      PushMessageModel model = PushMessageModel.modelFromReceiveUmengPush(result, false);
      await appController.insertMessage(model);
      await LocalNotifications.send(title: '自定义消息', body: result);
    }, (result) {
      print("打开消息：$result");
      showDialog(context: Get.context!, builder: (context) {
        return AlertDialog(
          title: const Text('打开消息'),
          content: Text(result),
          actions: <Widget>[
            TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('好的')
            ),
          ],
        );
      });
    });

    // 自定义消息回调
    UmengPushSdk.setMessageCallback((result)  async {
      print("接收到自定义消息: $result");
      AppController appController = Get.put(AppController());
      PushMessageModel model = PushMessageModel.modelFromReceiveUmengPush(result, true);
      await appController.insertMessage(model);
    });
  }

  /// 设置标签
  static Future<void> setTag(String tag) async {
    if (tag.isEmpty) {
      await PushManagerSP.removeTagLocal();
      return;
    }

    String? localTag = await PushManagerSP.getTagLocal();
    if (tag == localTag) {
      return;
    }

    bool? flag = false;
    flag = await UmengPushSdk.addTags([tag]);
    print('>>> UmengPushSdk.addTags返回:$flag');
    flag = await PushManagerSP.saveTagLocal(tag);
    print('>>> PushManagerSP.saveTagLocal返回:$flag');

    AppController appController = Get.put(AppController());
    appController.tag.value = tag;
  }

  /// 设置别名
  static Future<void> setAlias(String alias) async {
    if (alias.isEmpty) {
      await PushManagerSP.removeAliasLocal();
      return;
    }

    String? localAlias = await PushManagerSP.getAliasLocal();
    if (alias == localAlias) {
      return;
    }

    bool? flag = false;
    flag = await UmengPushSdk.setAlias(alias, _Channel);
    print('>>> UmengPushSdk.setAlias返回:$flag');
    flag = await PushManagerSP.saveAliasLocal(alias);
    print('>>> PushManagerSP.saveAliasLocal 返回:$flag');

    AppController appController = Get.put(AppController());
    appController.alias.value = alias;
  }
}

extension PushManagerSP on PushManager {
  static const _aliasKey = "sp_alias";
  static const _tagKey = "sp_tag";

  static Future<bool> saveAliasLocal(String alias) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return await sp.setString(_aliasKey, alias);
  }

  static Future<void> removeAliasLocal() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    await sp.remove(_aliasKey);
  }

  static Future<String?> getAliasLocal() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp.getString(_aliasKey);
  }

  static Future<bool> saveTagLocal(String tag) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return await sp.setString(_tagKey, tag);
  }

  static Future<void> removeTagLocal() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    await sp.remove(_tagKey);
  }

  static Future<String?> getTagLocal() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp.getString(_tagKey);
  }
}